package com.martin.lib_base.ui.screen

import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.martin.lib_base.ui.theme.CommonTheme

/**
 * @author：孟凡华
 * @date：2023/6/30
 * @desc：
 */

/**
 * 通用的底部弹出 Dialog
 */
@Composable
fun CommonBottomDialog(
    show: Boolean,
    onDismissRequest: () -> Unit,
    // 弹窗属性
    properties: DialogProperties = DialogProperties(usePlatformDefaultWidth = false),
    content: @Composable () -> Unit,
) {
    CommonDialog(
        show = show,
        alignment = Alignment.BottomCenter,
        properties = properties,
        onDismissRequest = onDismissRequest
    ) {
        content()
    }
}

/**
 * 通用Dialog
 */
@Composable
fun CommonDialog(
    // 是否显示弹窗
    show: Boolean,
    // 关闭弹窗回调
    onDismissRequest: () -> Unit,
    // 弹窗位置
    alignment: Alignment = Alignment.Center,
    // 弹窗属性
    properties: DialogProperties = DialogProperties(usePlatformDefaultWidth = false),
    // 弹窗内容
    content: @Composable BoxScope.() -> Unit,
) {
    if (show) {
        Dialog(
            onDismissRequest = onDismissRequest,
            properties = properties,
        ) {
            CommonTheme(null) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .clickableNoRipple {
                            if (properties.dismissOnClickOutside) {
                                onDismissRequest()
                            }
                        }
                ) {
                    Box(
                        modifier = Modifier
                            .align(alignment)
                            .clickableNoRipple { }
                    ) {
                        content()
                    }
                }
            }
        }
    }
}

/**
 * 去除点击时的水波纹效果
 */
fun Modifier.clickableNoRipple(onClick: () -> Unit): Modifier =
    composed {
        clickable(
            indication = null,
            interactionSource = remember { MutableInteractionSource() }) {
            onClick()
        }
    }


